<?php
namespace plugins\goods\interfaceLib;

use cmf\controller\PluginAdminBaseController;
use plugins\goods\model\GoodsModel;
use plugins\goods\model\GoodsSpecListModel;
use plugins\goods\model\GoodsSpecModel;
use plugins\store\Common;
use think\Db;

class GoodsSpecClassify extends PluginAdminBaseController
{
    /**
     * 初始化
     */
    protected function _initialize()
    {
    }
    //分类调用增加规格
    public function catCreateSpec($cid)
    {
        if (empty($cid)) {
            return api_json_echo(false, '传入的数据不正确，请检查');
        }
        $check = db('goods_spec')->where(['cat_id' => $cid])->find();
        if ($check) {
            $return = db('goods_spec')->insert(['cat_id' => $cid]);
            if ($return) {
                return ['status' => true, 'message' => '添加成功'];
            }
        } else {
            return ['status' => false, 'message' => '该分类已有规格'];
        }
        return ['status' => false, 'message' => '添加失败'];
    }
    //删除规格
    public function catDelSpec($cid)
    {
        if (empty($cid)) {
            return ['status' => false, 'message' => '传入的数据不正确，请检查'];
        }
        db('goods_spec')->where(['cat_id' => $cid])->delete();
        return ['status' => true, 'message' => '删除完成'];
    }

    /**
     * 根据模板id获取规格信息
     */
    public function getSpecAttr()
    {
        $data = $this->request->param();

        $id = $data['id'];

        $spec_name = db('goods_spec_name')->where('spec_id', $id)->select()->toArray();

        $da = [];
        //根据规格名获取属性列表
        foreach ($spec_name as $key => $value) {
            $da[$key]['name_id']   = $value['name_id'];
            $da[$key]['spec_name'] = $value['spec_name'];
            $da[$key]['spec_id']   = $value['spec_id'];

            $attr             = db('goods_spec_attr')->where('name_id', $value['name_id'])->select()->toArray();
            $da[$key]['attr'] = $attr;
        }

        return $this->success('成功', '', $da);
    }

    /**
     * 获取规格列表
     */
    public function getSpecList($store_id)
    {
        $where = 1;
        if (!empty($store_id)) {
            $where .= " and store_id = '{$store_id}'";
        } else {
            $is_admin = Common::getAllowAccess();
            if (true !== $is_admin) {
                $where .= " and store_id = '{$is_admin}'";
            } else {
                $where .= " and store_id = 'admin'";
            }
        }

        $spec_list = db('goods_spec')->where($where)->select()->toArray();
        return $spec_list;
    }

    /**
     * 规格独立版
     */
    public function pidGetSpecs($name, $id = null)
    {
        $gid = $id;
        //获取商品信息
        $good      = db('goods')->where(['id' => $id])->find();
        $spec_id   = $good['spec_temp'];
        $attr_html = $this->getSpecAttrHtml($name, $gid, $spec_id);

        $this->assign('spec_id', $spec_id);
        $this->assign('attr_html', $attr_html);
        $this->assign('name', $name);
        $spec_list = $this->getSpecList($good['store_id']);
        $this->assign('spec_list', $spec_list);
        return $this->fetch('goods_spec/pidGetSpecs');
    }

    public function getSpecAttrHtml($name, $id = null, $spec_id = null)
    {
        $gid  = $id;
        $spec = db('goods_spec')->where(['spec_id' => $spec_id])->find();
        //cid获得商品规格
        $model = new GoodsSpecModel();
        $model->setinfo($spec['spec_id']);
        $info = $model->info;
        //没有规格时自动返回
        if (empty($info['spec_id'])) {

            return "<div id='spec'><script>var url_set='" . cmf_get_root() . "';</script><input type='hidden' name='name' id='name' value='" . $name . "'><div class='layui-form-item'><label class='layui-form-label'></label><div>商品未配置规格</div></div></div>";
        }
        //gid获得已有配置
        $configs = db('goods_spec_list')->where(['gid' => $gid])->select()->toArray();
        //全部被选中存储
        $selected = [];
        foreach ($configs as $key => &$value) {
            //已选中的部分
            $arr              = explode("#*_*#", $value['attr']);
            $value['attr_id'] = $arr;
            foreach ($arr as $k => &$v) {
                $selected[] = $v;
                $attr_name  = db('goods_spec_attr')->where(['attr_id' => $v])->find();
                $v          = $attr_name['attr_name'];
            }
            $value['attr_name'] = $arr;
        }
        //选项栏
        $selectstr = '';
        $selectstr = $this->createcheckbox($name, $info, $selected);
        //表格
        $tablestr = '';
        $tablestr = $this->createspectable($name, $info, $configs);
        return "<div id='spec'>" . $selectstr . $tablestr . "</div><script>var url_set='" . cmf_get_root() . "';</script>";
    }

    //传入商品id获得规格并转到界面
    public function pidGetSpec($name, $id = null, $cid = null)
    {
        $gid = $id;

        $good = db('goods')->where(['id' => $id])->find();
        if ($cid == null) {
            $cid = $good['catid'];
        }
        $where = 1;

        if (!empty($good['store_id'])) {
            $where .= " and store_id = '" . $good['store_id'] . "'";
        } else {
            $is_admin = Common::getAllowAccess();
            if (true !== $is_admin) {
                $where .= " and store_id = '{$is_admin}'";
            }
        }
        $spec = db('goods_spec')->where($where)->where(['cid' => $cid])->find();

        //cid获得商品规格
        $model = new GoodsSpecModel();
        $model->setinfo($spec['spec_id']);
        $info = $model->info;
        //没有规格时自动返回
        if (empty($info['spec_id'])) {
            // return "<div id='spec'><input type='hidden' name='name' id='name' value='".$name."'><div class='layui-form-item'><label class='layui-form-label'></label><div>该分类未配置规格</div></div></div><script type='text/javascript' src='/plugins/goods/view/goods_spec/public.js'></script>";
            return "<div id='spec'><script>var url_set='" . cmf_get_root() . "';</script><input type='hidden' name='name' id='name' value='" . $name . "'><div class='layui-form-item'><label class='layui-form-label'></label><div>该分类未配置规格</div></div></div><div style='display:none;' class='__is_autoload_js_file__'>" . cmf_get_root() . "/plugins/goods/view/goods_spec/public.js</div>";

        }
        //gid获得已有配置
        $configs = db('goods_spec_list')->where(['gid' => $gid])->select()->toArray();
        //全部被选中存储
        $selected = [];
        foreach ($configs as $key => &$value) {
            //已选中的部分
            $arr              = explode("#*_*#", $value['attr']);
            $value['attr_id'] = $arr;
            foreach ($arr as $k => &$v) {
                $selected[] = $v;
                $attr_name  = db('goods_spec_attr')->where(['attr_id' => $v])->find();
                $v          = $attr_name['attr_name'];
            }
            $value['attr_name'] = $arr;
        }
        //选项栏
        $selectstr = '';
        $selectstr = $this->createcheckbox($name, $info, $selected);
        //表格
        $tablestr = '';
        $tablestr = $this->createspectable($name, $info, $configs);

        return "<div id='spec'>" . $selectstr . $tablestr . "</div><script>var url_set='" . cmf_get_root() . "';</script><div style='display:none;' class='__is_autoload_js_file__'>" . cmf_get_root() . "/plugins/goods/view/goods_spec/public.js</div>";
    }

    //创建初始头部
    private function createcheckbox($name, $info, $selected)
    {
        $selectstr = '';
        $selectstr .= "<input type='hidden' name='name' value='" . $name . "' />";
        $selectstr .= "<div class='layui-form-item'><label class='layui-form-label'>商品规格</label><div class='layui-input-block'>";
        foreach ($info['name'] as $key => $value) {
            $selectstr .= "<div>" . $value['spec_name'] . "：";
            foreach ($value['attr'] as $k => $v) {
                //点击控件
                $selectstr .= "<input type='checkbox' name='" . $value['name_id'] . "' class='check-btn' value='" . $v['attr_id'] . "' title='" . $v['attr_name'] . "' ";
                if (in_array($v['attr_id'], $selected)) {
                    $selectstr .= "checked";
                }
                $selectstr .= " />";
            }
            $selectstr .= "</div>";
        }
        $selectstr .= "</div></div>";
        return $selectstr;
    }
    //创建初始表格
    private function createspectable($name, $info, $configs)
    {
        $tablestr = '';
        $tablestr = "<div id='spec_table'>";
        if (!empty($configs)) {
            $tablestr .= "<div class='layui-form-item'><label class='layui-form-label'></label><form class='layui-form' action=''><table class='layui-table'><tr>";
            if (!empty($configs)) {
                //生成表格头
                foreach ($info['name'] as $key => $value) {
                    foreach ($value['attr'] as $k => $v) {
                        if (in_array($v['attr_id'], $configs[0]['attr_id'])) {
                            $tablestr .= "<th>" . $value['spec_name'] . "</th>";
                        }
                    }
                }
            } else {
                //生成表格头
                foreach ($info['name'] as $key => $value) {
                    $tablestr .= "<th>" . $value['spec_name'] . "</th>";
                }
            }
            $tablestr .= "<th>销售价格</th><th>商品库存</th><th>库存预警值</th><th>上传图片</th><th>sku</th></tr>";
            //两次循环得到内容
            foreach ($configs as $key => $value) {

                // $src_img = $value['img'] ? cmf_get_root() . "/plugins/goods/view/image/" . $value['img'] : '';
                $src_img = $value['img'] ? zy_domain().$value['img'] : '';

                $tablestr .= "<tr>";
                //生成行的头部
                foreach ($value['attr_name'] as $k => $v) {
                    $tablestr .= "<td>" . $v . "</td>";
                }
                $attr = '';
                $tablestr .= "<td><input type='text' name='" . $name . "[price][]' placeholder='' autocomplete='off' class='layui-input' value='" . $value['price'] . "' /></td>";
                $tablestr .= "<td><input type='text' name='" . $name . "[num][]' placeholder='' autocomplete='off' class='layui-input' value='" . $value['num'] . "' /></td>";
                $tablestr .= "<td><input type='text' name='" . $name . "[limit][]' placeholder='' autocomplete='off' class='layui-input' value='" . $value['limit'] . "' /></td>";
                //图片
                $tablestr .= "<td>";
                $tablestr .= "<input type='hidden' name='" . $name . "[img][]' placeholder='' autocomplete='off' class='layui-input' value='" . $value['img'] . "' />";
                $tablestr .= "<img src='" . $src_img . "' name='img' /><br />";
                $tablestr .= "<button type='button' class='layui-btn upimg'  lay-data='{data:{info:\"spec_img\"}}'>上传图片</button>";
                $tablestr .= "</td>";
                // $tablestr .= "<td><input type='text' name='".$name."[img][]' placeholder='' autocomplete='off' class='layui-input' value='".$value['img']."'></td>";
                //sku
                $tablestr .= "<td><input type='text' name='" . $name . "[sku][]' placeholder='不输入时自动生成' autocomplete='off' class='layui-input' value='" . $value['sku'] . "' /></td>";
                // $tablestr .= "<td></td>";
                //属性名称
                $tablestr .= "<input type='hidden' name='" . $name . "[attr][]' placeholder='' autocomplete='off' class='layui-input' value='" . $value['attr'] . "' />";
                //id
                $tablestr .= "<input type='hidden' name='" . $name . "[id][]' placeholder='' autocomplete='off' class='layui-input' value='" . $value['id'] . "' />";
                $tablestr .= "</tr>";
            }
        }
        $tablestr .= "</table>";
        $tablestr .= "</div>";
        $tablestr .= "</div>";
        return $tablestr;
    }
    //选择后生成的表格
    public function cartesiantable($data, $name)
    {
        $arr         = [];
        $title       = [];
        $attr_id     = [];
        $arr_name_id = [];
        //规格name数组
        $names = [];
        foreach ($data as $key => $value) {
            if (empty($value)) {
                continue;
            }
            $arr[]         = $value;
            $arr_name_id[] = $key;
            $info          = db('goods_spec_name')->where(['name_id' => $key])->find();
            $names[]       = $info['spec_name'];
        }
        foreach ($arr as $key => $value) {
            foreach ($value as $k => $v) {
                $title[$key][]   = $v['title'];
                $attr_id[$key][] = $v['attr_id'];
            }
        }
        $title_list = $this->cartesian($title);
        $attr_list  = $this->cartesian($attr_id);
        $return     = [];
        foreach ($title_list as $key => $value) {
            $return[] = explode('#*_*#', $value);
        }
        //生成内容
        $tablestr = '';
        $tablestr .= "<div class='layui-form-item'><label class='layui-form-label'></label><form class='layui-form' action=''><table class='layui-table'><tr>";
        foreach ($names as $key => $value) {
            $tablestr .= "<th>" . $value . "</th>";
        }
        $tablestr .= "<th>销售价格</th><th>商品库存</th><th>库存预警值</th><th>上传图片</th><th>sku</th></tr>";
        //两次循环得到内容
        foreach ($return as $key => $value) {
            $tablestr .= "<tr>";
            //生成行的头部
            foreach ($value as $k => $v) {
                $tablestr .= "<td>" . $v . "</td>";
            }
            $attr = '';
            $tablestr .= "<td><input type='text' name='" . $name . "[price][]' placeholder='' autocomplete='off' class='layui-input' value='' /></td>";
            $tablestr .= "<td><input type='text' name='" . $name . "[num][]' placeholder='' autocomplete='off' class='layui-input' value='' /></td>";
            $tablestr .= "<td><input type='text' name='" . $name . "[limit][]' placeholder='' autocomplete='off' class='layui-input' value='' /></td>";
            //图片
            $tablestr .= "<td>";
            $tablestr .= "<input type='hidden' name='" . $name . "[img][]' placeholder='' autocomplete='off' class='layui-input' value='' />";
            $tablestr .= "<img src='' name='img'><br>";
            $tablestr .= "<button type='button' class='layui-btn upimg'  lay-data='{data:{info:\"spec_img\"}}'>上传图片</button>";
            $tablestr .= "</td>";
            //sku
            $tablestr .= "<td><input type='text' name='" . $name . "[sku][]' placeholder='不输入时自动生成' autocomplete='off' class='layui-input' value='' /></td>";
            $tablestr .= "<input type='hidden' name='" . $name . "[attr][]' placeholder='' autocomplete='off' class='layui-input' value='" . $attr_list[$key] . "' />";
            $tablestr .= "<input type='hidden' name='" . $name . "[id][]' placeholder='' autocomplete='off' class='layui-input' value='' />";
            $tablestr .= "</tr>";
        }
        $tablestr .= "</table>";
        return $tablestr;
    }
    /**
     ** 实现二维数组的笛卡尔积组合
     ** $arr 要进行笛卡尔积的二维数组
     ** $str 最终实现的笛卡尔积组合,可不写
     ** @return array
     **/
    private function cartesian($arr = [], $str = array())
    {
        if (empty($arr)) {
            return [];
        }
        //去除第一个元素
        $first = array_shift($arr);
        //判断是否是第一次循环
        if (count($str) >= 1) {
            foreach ($str as $k => $val) {
                foreach ($first as $key => $value) {
                    //最终实现的格式 1,3,76
                    //可根据具体需求进行变更
                    $str2[] = $val . '#*_*#' . $value;
                }
            }
        } else {
            foreach ($first as $key => $value) {
                //最终实现的格式 1,3,76
                //可根据具体需求进行变更
                $str2[] = $value;
            }
        }
        //递归进行拼接
        if (count($arr) > 0) {
            $str2 = $this->cartesian($arr, $str2);
        }
        //返回最终笛卡尔积
        return $str2;
    }
    //保存数据
    public function pidSaveSpec($param, $id)
    {
        $arr = [];

        foreach ($param as $key => $value) {
            foreach ($value as $k => $v) {
                $arr[$k][$key]  = $v;
                $arr[$k]['gid'] = $id;
            }
        }
        //循环结果
        foreach ($arr as $key => $value) {
            $arr[$key]['action'] = 1;
            if ($arr[$key]['sku'] == '') {
                $arr[$key]['sku'] = "sku_" . substr(uniqid(), 0, 6) . rand(1000, 9999);
            }
            if ($value['id'] == '') {
                unset($arr[$key]['id']);
            }
        }
        $model  = new GoodsSpecListModel();
        $result = $model->saveAll($arr);
        if ($result) {
            //删除未操作到的
            GoodsSpecListModel::destroy(['action' => 0, 'gid' => $id]);
            //更新修改标识
            GoodsSpecListModel::where('gid', $id)->update(['action' => 0]);
            return true;
        }
        return false;
    }

    //保存数据
    public function pidSaveSpecs($param, $id)
    {
        $arr       = [];
        $spec_temp = $param['spec_temp'];
        unset($param['spec_temp']);
        foreach ($param as $key => $value) {
            foreach ($value as $k => $v) {
                $arr[$k][$key]  = $v;
                $arr[$k]['gid'] = $id;
            }
        }
        //循环结果
        foreach ($arr as $key => $value) {
            $arr[$key]['action'] = 1;
            if ($arr[$key]['sku'] == '') {
                $arr[$key]['sku'] = "sku_" . substr(uniqid(), 0, 6) . rand(1000, 9999);
            }
            if ($value['id'] == '') {
                unset($arr[$key]['id']);
            }
        }
        $model  = new GoodsSpecListModel();
        $result = $model->saveAll($arr);

        //修改商品表规格模板
        try {
            $goods_spec = GoodsSpecModel::where('spec_id', $spec_temp)->find();
            $goods      = GoodsModel::get(['id' => $id]);
            if (isset($goods->catid)) {
                $goods->catid = $goods_spec['cid'];
            }
            $goods->spec_temp = $spec_temp;
            $goods->save();
        } catch (\Exception $e) {

        }

        if ($result) {
            //删除未操作到的
            GoodsSpecListModel::destroy(['action' => 0, 'gid' => $id]);
            //更新修改标识
            GoodsSpecListModel::where('gid', $id)->update(['action' => 0]);
            return true;
        }
        return false;
    }

}
